<template>

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="企业名称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          class="!w-240px"
          clearable
          placeholder="请输入企业名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="mark">
        <el-input
          v-model="queryParams.mark"
          class="!w-240px"
          clearable
          placeholder="请输入联系电话"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          class="!w-240px"
          clearable
          placeholder="请输入登录账号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 统计数据展示 -->
  <ContentWrap>
    <el-row class="mb-15px">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <Icon class="mr-5px" icon="ep:money" />
              <span>当前企业总数</span>
            </div>
            <div class="flex items-center">
              <span class="text-2xl font-bold">{{ unityCount?.userNum }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <Icon class="mr-5px" icon="ep:money" />
              <span>当前交易账户总数</span>
            </div>
            <div class="flex items-center">
              <span class="text-2xl font-bold">{{ unityCount?.creatorNum }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <Icon class="mr-5px" icon="ep:money" />
              <span>当前交易单元总数</span>
            </div>
            <div class="flex items-center">
              <span class="text-2xl font-bold">{{ unityCount?.unitNum }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="企业编号" prop="id" width="120px" />
	  <el-table-column align="center" label="企业名称" prop="nickname" width="120px" />
      <el-table-column align="center" label="联系人" prop="name" width="120px" />
      <el-table-column align="center" label="联系电话" prop="mark" width="80px" />
      <el-table-column align="center" label="登录账号" prop="mobile" width="100px" />
      <el-table-column
        :show-overflow-tooltip="false"
        align="center"
        label="交易账户"
        prop="tagNames"
      >
        <template #default="scope">
          <el-tag v-for="(tagName, index) in scope.row.jidy" :key="index" class="mr-5px">
            {{ tagName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="登录时间"
        prop="loginDate"
        width="180px"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="注册时间"
        prop="createTime"
        width="180px"
      />
      <el-table-column
        :show-overflow-tooltip="false"
        align="center"
        fixed="right"
        label="操作"
        width="100px"
      >
        <template #default="scope">
          <div class="flex items-center justify-center">
           <!-- 修改按钮点击事件 -->
           <el-button link type="primary" @click="openResetPasswordDialog(scope.row.mobile)">重置密码</el-button>
      </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 修改用户等级弹窗 -->
  <UserLevelUpdateForm ref="updateLevelFormRef" @success="getList" />
  <!-- 修改用户积分弹窗 -->
  <UserPointUpdateForm ref="updatePointFormRef" @success="getList" />
  <!-- 修改用户余额弹窗 -->
  <UserBalanceUpdateForm ref="UpdateBalanceFormRef" @success="getList" />
  <!-- 发送优惠券弹窗 -->
  <CouponSendForm ref="couponSendFormRef" />
</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE } from '@/utils/dict'
import UserForm from './UserForm.vue'
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberLevelSelect from '@/views/member/level/components/MemberLevelSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import UserLevelUpdateForm from './components/UserLevelUpdateForm.vue'
import UserPointUpdateForm from './components/UserPointUpdateForm.vue'
import UserBalanceUpdateForm from './components/UserBalanceUpdateForm.vue'
import { CouponSendForm } from '@/views/mall/promotion/coupon/components'
import { checkPermi } from '@/utils/permission'
import { resetPassword } from '@/api/member/user'
import { ElMessageBox } from 'element-plus'
import { TradingUnitApi, TradingUnitVO } from '@/api/dd/tradingunit'
defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  groupId: null,
  mark: null,
})
const queryFormRef = ref() // 搜索的表单
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const UpdateBalanceFormRef = ref() // 修改用户余额表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组
const unityCount = ref() // 交易单元数量


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log(queryParams)
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
  getTradingUnitCount()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  //弹窗输入新密码进行密码修改
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 发送优惠券 */
const couponSendFormRef = ref()
const openCoupon = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要发送优惠券的用户')
    return
  }
  couponSendFormRef.value.open(selectedIds.value)
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      UpdateBalanceFormRef.value.open(row.id)
      break
    default:
      break
  }
}

// 打开重置密码对话框
const openResetPasswordDialog = (id: number) => {
  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    // 假设密码长度为 6 - 20 位非空白字符,数字加字符
    inputPattern: /^(?=.*[A-Za-z])(?=.*\d)[\S]{6,20}$/, 

    inputErrorMessage: '密码长度应为 6 - 20 位非空白字符，且必须同时包含数字和字符'
  }).then(({ value }) => {
    if (value) {
      const passwordData = {
        mobile: id, // 假设需要用户 ID 来重置密码
        password: value,
        code:'123456'
      };
      console.log(passwordData)
      resetPasswordData(passwordData);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

/** 重置密码 */

const resetPasswordData = async (passwordData) => {

  // 调用重置密码接口
  
  try {
    await resetPassword(passwordData)
    message.success('重置密码成功')
  } catch (error) {
    message.error('重置密码失败')
  }
}

/**接口统计*/
const getTradingUnitCount = async () => {
  console.log(queryParams)
  const res = await TradingUnitApi.getCountDataData(queryParams)
  unityCount.value = res 
}


/** 初始化 **/
onMounted(() => {
  getList()
  getTradingUnitCount()
})
</script>
